// AUTHORS: Yiwei (Alan) Han, Kevin Lam

function ajaxUpdate(){
	if(getCookie('user') != null) {
	getFeedContent();
	getPendingFriend();
	getActiveFriend();
	setInterval( "ajaxUpdate();", 10000 );
	}
}



function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		alert("IE5/6 not supported");
	}
}

var feed_req = getXmlHttpRequestObject();

function getFeedContent() {
	if (feed_req.readyState == 4 || feed_req.readyState == 0) {
		feed_req.open("GET", 'auth/ajax/feeds?touch=false&type=all', true);
		feed_req.onreadystatechange = handleFeedContent;
		feed_req.send(null);
	}
}

function handleFeedContent() {
	if (feed_req.readyState == 4 && feed_req.responseXML != null) {
		var xmlDoc = feed_req.responseXML.documentElement;
		var content = document.getElementById('feeds');
		var msg = xmlDoc.getElementsByTagName("message");
		var feeds = '';
		for (i = 0; i < msg.length; i++) {
			var text = msg[i].getElementsByTagName("text")[0].childNodes[0].nodeValue;
			var timestamp = msg[i].getElementsByTagName("timestamp")[0].childNodes[0].nodeValue;
			var is_new = msg[i].getElementsByTagName("new")[0].childNodes[0].nodeValue;
			if(is_new == 'true')
				feeds += '<div class="feed_unread">';
			if(is_new == 'false')
				feeds += '<div class="feed_read">';
			feeds += '<div class="feed_body"><p>'+text+'</p></div>' + '<br><div class="feed_time">' + timestamp + '</div></div>';
		}
		content.innerHTML = feeds;
	}
}

function postShow(){
	$('#friend-dialog').fadeOut(1000);
	$('#post-dialog').animate({ opacity: 'toggle' }, 1000);
	document.getElementById('post-area').focus();
}

function friendShow(){
	$('#post-dialog').fadeOut(1000);
	$('#friend-dialog').animate({ opacity: 'toggle' }, 1000);
}

function addFriendShow() {
	$('#add-friend-dialog').animate({ opacity: 'toggle' }, 1000);
	$('#feed-dimmer').fadeIn();
}

function addFriendClose() {
	$('#add-friend-dialog').fadeOut(300);
	$('#feed-dimmer').fadeOut();
}

var post_req = getXmlHttpRequestObject();

function tryPost(){
	var user = getCookie('user'); 
	if(user != null) {
	var postcontent = encodeURIComponent(user+': '+document.getElementById('post-area').value);
		if (post_req.readyState == 4 || post_req.readyState == 0) {
			post_req.open("GET", 'auth/ajax/subscribe?action=publish&msg='+postcontent, true);
			post_req.onreadystatechange = handlePost;
			post_req.send(null);
		}
	}
}

function handlePost(){
	if (post_req.readyState == 4) {
		var xmlDoc = post_req.responseXML;
		var content = document.getElementById('post-error');
		var response = xmlDoc.getElementsByTagName("response")[0].childNodes[0].nodeValue;
		var type = xmlDoc.getElementsByTagName("type")[0].childNodes[0].nodeValue;
		if(type == 'false')
			content.className = 'post-error_red';
		else
			content.className = 'post-error_green';
		content.innerHTML = '<p class="post-error_text">'+response+'</p>';
		$('#post-error').fadeIn(500).delay(3000).fadeOut(500);
		$('#post-dialog').fadeOut();
	}
	
}

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

var friend_pending_req = getXmlHttpRequestObject();

function getPendingFriend(){
	var user = getCookie('user'); 
	if(user != null) {
		if (friend_pending_req.readyState == 4 || friend_pending_req.readyState == 0) {
			friend_pending_req.open("GET", 'auth/ajax/subscribe?action=subscriptions&type=pending', true);
			friend_pending_req.onreadystatechange = handlePendingFriendContent;
			friend_pending_req.send(null);
		}
	}
}

function handlePendingFriendContent(){
	if (friend_pending_req.readyState == 4) {
		var xmlDoc = friend_pending_req.responseXML;
		var content = document.getElementById('friend-pending');
		var response = '';
		if(xmlDoc.getElementsByTagName("response")[0].hasChildNodes()) {
			var parent = xmlDoc.getElementsByTagName("response")[0].getElementsByTagName("subscription");
			for(var i = 0; i < parent.length; i++){
				var email = parent[i].getElementsByTagName("email")[0].childNodes[0].nodeValue;
				var status = parent[i].getElementsByTagName("status")[0].childNodes[0].nodeValue;
				if(status == 'Waiting')
					response += '<div class="friend-item"><p style="text-align:left; float: left;">'+email+'</p><span class="friend-pending-button">Invitation Sent</span></div>';
				if(status == 'Pending')
					response += '<div class="friend-item"><p style="text-align:left; float: left;">'+email+'</p><span class="friend-pending-button" onclick="acceptFriend(\''+email+'\');" >Accept</span><span class="friend-pending-button" onclick="declineFriend(\''+email+'\');">Decline</span></p></div>';
			}
		}
		if(response == '')
			response = '<div class="friend-item">No pending friend requests</div>';
		content.innerHTML = response;
	}
	
}

var friend_active_req = getXmlHttpRequestObject();

function getActiveFriend(){
	var user = getCookie('user'); 
	if(user != null) {
		if (friend_active_req.readyState == 4 || friend_active_req.readyState == 0) {
			friend_active_req.open("GET", 'auth/ajax/subscribe?action=subscriptions&type=active', true);
			friend_active_req.onreadystatechange = handleActiveFriendContent;
			friend_active_req.send(null);
		}
	}
}

function handleActiveFriendContent(){
	if (friend_active_req.readyState == 4) {
		var xmlDoc = friend_active_req.responseXML;
		var content = document.getElementById('friend-list');
		var response = '';
		if(xmlDoc.getElementsByTagName("response")[0].hasChildNodes()) {
			var parent = xmlDoc.getElementsByTagName("response")[0].getElementsByTagName("subscription");
			for(var i = 0; i < parent.length; i++){
				var email = parent[i].getElementsByTagName("email")[0].childNodes[0].nodeValue;
				var status = parent[i].getElementsByTagName("status")[0].childNodes[0].nodeValue;
				response += '<div class="friend-item" onclick="window.location=\'/worklist?email='+email+'\'"><p style="text-align:left">'+email+'</p></div>';
			}
		}
		else
			response = '<div class="friend-item"><img src="http://media.tumblr.com/tumblr_lf5dx6V1Na1qdavox.png"/></div>';
		content.innerHTML = response;
	}	
}

var add_friend_req = getXmlHttpRequestObject();

function addFriend(){
	var email = document.getElementById("friend-email").value;
	if (add_friend_req.readyState == 4 || add_friend_req.readyState == 0) {
		add_friend_req.open("GET", 'auth/ajax/subscribe?action=add&email='+email, true);
		add_friend_req.onreadystatechange = handleAddFriend;
		add_friend_req.send(null);
	}
}

function handleAddFriend(){
	if (add_friend_req.readyState == 4) {
		var xmlDoc = add_friend_req.responseXML;
		var content = document.getElementById('friend-error');
		var response = xmlDoc.getElementsByTagName("response")[0].childNodes[0].nodeValue;
		content.innerHTML = '<p class="post-error_text">'+unescape(response)+'</p>';
		$('#friend-error').fadeIn(500).delay(3000).fadeOut(500);
	}
}

var accept_friend_req = getXmlHttpRequestObject();

function acceptFriend(email){
	if (accept_friend_req.readyState == 4 || accept_friend_req.readyState == 0) {
		accept_friend_req.open("GET", 'auth/ajax/subscribe?action=accept&email='+email, true);
		accept_friend_req.onreadystatechange = handleAcceptFriend;
		accept_friend_req.send(null);
	}
}

function handleAcceptFriend(){
	if (accept_friend_req.readyState == 4) {
		var xmlDoc = accept_friend_req.responseXML;
		var content = document.getElementById('friend-error');
		var response = xmlDoc.getElementsByTagName("response")[0].childNodes[0].nodeValue;
		content.innerHTML = '<p class="post-error_text">'+unescape(response)+'</p>';
		$('#friend-error').fadeIn(500).delay(3000).fadeOut(500);
	}
}

var decline_friend_req = getXmlHttpRequestObject();

function declineFriend(email){
	if (decline_friend_req.readyState == 4 || decline_friend_req.readyState == 0) {
		decline_friend_req.open("GET", 'auth/ajax/subscribe?decline=add&email='+email, true);
		decline_friend_req.onreadystatechange = handleDeclineFriend;
		decline_friend_req.send(null);
	}
}

function handleDeclineFriend(){
	if (decline_friend_req.readyState == 4) {
		var xmlDoc = decline_friend_req.responseXML;
		var content = document.getElementById('friend-error');
		var response = xmlDoc.getElementsByTagName("response")[0].childNodes[0].nodeValue;
		content.innerHTML = '<p class="post-error_text">'+unescape(response)+'</p>'; 
		$('#friend-error').fadeIn(500).delay(3000).fadeOut(500);
	}
}